<template>
  <div
    class="flex h-100% ml-20px"
    style="background-color: #fff; border-radius: 10px"
  >
    <DepartmentTree
      ref="departmentTreeRef"
      @node-change="handleNodeChange"
      @upload-packet="handleFileChange"
      @task-change="handleTaskChange"
    />

    <div
      class="tableManage"
      style="width: calc(100% - var(--left-tree-max-width))"
    >
      <ContentWrap class="ml-10px flex flex-col">
        <div v-if="deviceTreeStore.taskInfo?.missionCode">
          <div class="flex justify-between mb-15px align-center">
            <div class="f-s16 font-bold">任务详情</div>
            <div class="flex">
              <BaseButton
                class="opBtn"
                size=""
                type="primary"
                @click="exportAction"
              >
                导出数据包
              </BaseButton>
              <el-upload
                ref="uploadRef"
                :auto-upload="false"
                :show-file-list="false"
                :accept="'.xlsx,.xls'"
                :on-change="(file) => handleFileSelect(file, 'data')"
              >
                <BaseButton class="opBtn mx-12px" size="" type="primary"
                  >导入excel文件</BaseButton
                >
              </el-upload>
              <BaseButton
                class="opBtn"
                size=""
                type="primary"
                @click="exportActionExcel"
              >
                下载excel模板
              </BaseButton>
            </div>
          </div>
          <el-descriptions :column="4" border>
            <template slot="extra"> </template>
            <el-descriptions-item label="任务名">
              {{ taskInfos.name }}
            </el-descriptions-item>
            <el-descriptions-item label="数据包导出人员">
              {{ taskInfos.superiorUserName }}
            </el-descriptions-item>
            <el-descriptions-item label="有效日期截止">
              {{ taskInfos.validTime }}
            </el-descriptions-item>

            <el-descriptions-item label="成品厂名称">
              {{ taskInfos.collectorUserName }}
            </el-descriptions-item>
            <el-descriptions-item label="成品厂导入时间">
              {{ taskInfos.collectorImportTime }}
            </el-descriptions-item>
            <el-descriptions-item label="成品厂导出时间">
              {{ taskInfos.collectorExportTime }}
            </el-descriptions-item>
            <el-descriptions-item label="成品厂审批人">
              {{ taskInfos.approver }}
            </el-descriptions-item>
            <el-descriptions-item label="成品厂审批时间">
              {{ taskInfos.approveTime }}
            </el-descriptions-item>
          </el-descriptions>
          <div class="line"></div>

          <!-- <ElDivider /> -->
        </div>
        <el-tabs
          v-model="activeName"
          class=""
          @tab-click="handleClick"
        >
          <el-tab-pane
            v-for="tab in tabs"
            :key="tab.name"
            :label="tab.label"
            :name="tab.name"
          >
            <component
              v-if="activeName === tab.name"
              :is="tab.component"
              :current-node-key="currentNodeKey"
              :currentNode="currentNode"
              :type="tab.type"
              :ref="(el) => (componentRefs[tab.name] = el)"
            />
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>
    </div>

    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <!-- 查看详情 -->
      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow"
      />

      <!-- 创建采集任务 -->
      <Task
        :stepsNum="stepsNum"
        v-if="actionType === 'task'"
        ref="taskRef"
        :show-checkbox="true"
      />

      <!-- 对话框底部按钮 -->
      <template #footer>
        <!-- <BaseButton v-if="productStore.productMarketStep > 0" @click="prevStep"
          >上一步</BaseButton
        > -->
        <BaseButton v-if="productStore.productMarketStep < 3" @click="nextStep"
          >下一步</BaseButton
        >
        <BaseButton
          v-if="productStore.productMarketStep === 3"
          type="primary"
          :loading="saveLoading"
          @click="saveTask"
          >导出数据包</BaseButton
        >
        <BaseButton @click="dialogVisible = false">关闭</BaseButton>
      </template>
    </Dialog>

    <Dialog v-model="resultDialogVisible" :title="importTitle" width="50%">
      <div v-if="logCodeFlag">
        <div class="f-s16 mb-8px">
          <div class="flex justify-between f-s16 font-700">
            错误信息：<BaseButton
              class="opBtn"
              size=""
              type="primary"
              v-if="logCode !== '' && logCode !== null"
              @click="logAction(logCode)"
            >
              下载日志
            </BaseButton>
          </div>
          <div class="error-item mt-20px">{{ logCodeTitle }}</div>
        </div>
      </div>
      <div v-else>
        <div v-if="importResult" class="success-message">
          <!-- 成功消息内容 -->
          <div
            v-for="(item, index) in importSuccessMessage"
            :key="index"
            class="f-s16 mb-8px"
          >
            {{ index + 1 }} .{{ item }}
          </div>
        </div>

        <div class="import-result" v-else>
          <div
            class="import-result-container"
            :style="{ height: resultContainerHeight }"
          >
            <el-tabs
              v-model="activeName1"
              v-loading="importLoading"
              class="demo-tabs full-height-tabs"
            >
              <el-tab-pane
                v-for="(value, index) in tabs1"
                :key="index"
                :label="value.tab"
                :name="value.tab"
              >
                <!-- 移除外层的 flex 布局，使用简单的固定高度 -->
                <div class="error-content-wrapper">
                  <div
                    v-if="value.errors && value.errors.length > 0"
                    class="error-details"
                  >
                    <div class="mb-10px flex justify-between f-s16 font-700">
                      错误信息：<BaseButton
                        class="opBtn"
                        size=""
                        type="primary"
                        v-if="logCode !== '' && logCode !== null"
                        @click="logAction(logCode)"
                      >
                        下载日志
                      </BaseButton>
                    </div>
                    <div
                      class="error-item"
                      v-for="(error, errorIndex) in value.errors"
                      :key="errorIndex"
                    >
                      <h4 class="mb-10px">{{ error.dataRow }}:</h4>
                      <p
                        class="mb-5px"
                        v-for="(item, i) in error.errors"
                        :key="i"
                      >
                        {{ item }}
                      </p>
                    </div>
                  </div>
                  <div v-else class="no-errors">没有错误信息</div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>

      <template #footer>
        <BaseButton type="primary" @click="resultDialogVisible = false">
          确定
        </BaseButton>
      </template>
    </Dialog>
    <!-- </ContentWrap> -->
  </div>
</template>

<script setup lang="tsx">
import { ref, shallowRef, onBeforeUnmount, reactive } from "vue";
import { ContentWrap } from "@/components/ContentWrap";
import { useProductStore } from "@/store/modules/task";
import type {
  DepartmentItem,
  DepartmentUserItem,
} from "@/components/DepartmentTree/types";

import DepartmentTree from "@/components/DepartmentTree/taskIndex.vue";

import { useDepartmentStore } from "@/store/modules/departmentStore";

import {
  ElMessage,
  ElMessageBox,
  ElTree,
  ElUpload,
  UploadFile,
  UploadInstance,
  absPaneContext,
} from "element-plus";

// 导入各个组件（请根据实际路径调整）
import DomesticComponents from "@/views/productDataManagement/domesticComponents/index.vue"; //国产元器件
import ImportedComponents from "@/views/productDataManagement/importedComponents/index.vue"; //进口元器件
import DomesticMaterials from "@/views/productDataManagement/domesticMaterials/index.vue"; //国产材料
import ImportedMaterials from "@/views/productDataManagement/importedMaterials/index.vue"; //进口材料
import DomesticMeProducts from "@/views/productDataManagement/domesticMeProducts/index.vue"; // 国产机电产品
import ImportedMeProducts from "@/views/productDataManagement/importedMeProducts/index.vue"; // 国产机电产品
import DomesticSoftware from "@/views/productDataManagement/domesticSoftware/index.vue"; //国产软件
import ImportedSoftware from "@/views/productDataManagement/importedSoftware/index.vue"; //进口软件
import { useDeviceTreeStore } from "@/store/modules/deviceTreeStore";

// 添加响应式高度控制
const resultContainerHeight = ref("400px"); // 默认高度
const errorContentHeight = ref("300px"); // 错误内容区域高度

const calculateHeights = () => {
  const windowHeight = window.innerHeight;
  const dialogHeight = windowHeight * 0.7;
  resultContainerHeight.value = `${dialogHeight - 120}px`;
  errorContentHeight.value = `${dialogHeight - 250}px`; // 调整这个值，为 tabs 头部留出空间
};
const departmentStore = useDepartmentStore();
const productStore = useProductStore();
const deviceTreeStore = useDeviceTreeStore();
// 从store中获取当前节点key
const currentNodeKey = ref(departmentStore.currentNodeKey);
const logCodeFlag = ref(false);
const logCodeTitle = ref("");
const taskInfos = ref({
  name: "",
  superiorUserName: "",
  validTime: "",
  collectorUserName: "",
  collectorImportTime: "",
  collectorExportTime: "",
  approver: "",
  approveTime: "",
  superiorImportTime: "",
});
const handleTaskChange = (taskInfo) => {
  taskInfos.value = taskInfo;
};

// 获取部门树组件引用
const departmentTreeRef = ref<InstanceType<typeof DepartmentTree>>();
const currentNode = ref();
// 处理部门树节点变化
const handleNodeChange = (node: DepartmentItem) => {
  currentNode.value = node.departmentName;
  currentNodeKey.value = node.id;
};
const logCode = ref("");
// 动态标签页配置
const tabs = ref([
  {
    label: "国产元器件",
    name: "domesticComponents",
    component: shallowRef(DomesticComponents),
  },
  {
    label: "进口元器件",
    name: "importedComponents",
    component: shallowRef(ImportedComponents),
  },
  {
    label: "国产材料",
    name: "domesticMaterial",
    component: shallowRef(DomesticMaterials),
    type: "domestic",
  },
  {
    label: "进口材料",
    name: "importedMaterial",
    component: shallowRef(ImportedMaterials),
    type: "imported",
  },
  {
    label: "国产机电产品",
    name: "domesticElectromechanical",
    component: shallowRef(DomesticMeProducts),
    type: "domestic",
  },
  {
    label: "进口机电产品",
    name: "importedElectromechanical",
    component: shallowRef(ImportedMeProducts),
    type: "imported",
  },
  {
    label: "国产软件",
    name: "domesticSoftware",
    component: shallowRef(DomesticSoftware),
    type: "domestic",
  },
  {
    label: "进口软件",
    name: "importedSoftware",
    component: shallowRef(ImportedSoftware),
    type: "imported",
  },
]);

// 默认激活第一个标签
const activeName = ref(tabs.value[0].name);

const handleClick = (tab, event: Event) => {
  console.log("切换标签:", tab.props.name, event);
};
// 对话框相关
const dialogVisible = ref(false);
const tabs1 = ref();
const activeName1 = ref("");
const actionType = ref("");
const saveLoading = ref(false);

/**
 * 处理文件导入
 * @param file 上传的文件对象
 */

// 导入相关
const resultDialogVisible = ref(false);
const uploadRef = ref<UploadInstance>();
const selectedFile = ref<File | null>(null);
const importLoading = ref(false);

// 导入结果
const importResult = ref(false);
const importSuccessMessage = ref([]);
const importTitle = ref("");

/**
 * 文件选择验证
 */
const handleFileSelect = (file: UploadFile) => {
  // 验证文件类型
  if (!validateFileType(file)) {
    // 清空文件选择
    if (uploadRef.value) {
      uploadRef.value.clearFiles();
    }
    return false;
  }

  // 文件验证通过，继续处理
  handleFileChange(file, "data");
};

/**
 * 验证文件类型
 */
const validateFileType = (file: UploadFile) => {
  if (!file.raw) {
    ElMessage.error("文件不存在");
    return false;
  }

  // 检查文件扩展名
  const fileExtension = file.name.split(".").pop()?.toLowerCase();
  const allowedExtensions = ["xls", "xlsx"];

  if (!fileExtension || !allowedExtensions.includes(fileExtension)) {
    ElMessage.error("文件格式错误！只能上传 .xlsx 或 .xls 格式的Excel文件");
    return false;
  }

  // 检查MIME类型（可选，因为不同浏览器可能识别不同）
  const allowedMimeTypes = [
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "application/vnd.ms-excel.sheet.macroEnabled.12",
    "application/octet-stream", // 某些情况下可能是这个类型
  ];

  // 如果MIME类型不为空且不在允许列表中，给出警告但继续（因为扩展名正确）
  if (file.raw.type && !allowedMimeTypes.includes(file.raw.type)) {
    console.warn("文件MIME类型不匹配，但扩展名正确，继续处理");
  }

  // 限制文件大小（10MB）
  // const maxSize = 10 * 1024 * 1024; // 10MB
  // if (file.size && file.size > maxSize) {
  //   ElMessage.error('文件大小不能超过 10MB');
  //   return false;
  // }

  return true;
};

/**
 * 处理文件导入（原有的handleFileChange函数需要调整）
 */
const handleFileChange = async (file: UploadFile, type: string) => {
  console.log(file, type);

  if (type === "data") {
    // 这里不再需要验证，因为已经在handleFileSelect中验证过了
    logCodeFlag.value = false;
    ElMessageBox.confirm(
      "该操作会覆盖当前任务下的所有已填报项，确认继续？",
      "提示",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(async () => {
        if (!file.raw) {
          return;
        }

        selectedFile.value = file.raw;
        importLoading.value = true;
        resultDialogVisible.value = true;
        importTitle.value = "正在导入文件，请稍后...";
        try {
          const formData = new FormData();
          formData.append("file", file.raw);
          formData.append("deviceCode", currentNodeKey.value);
          formData.append("missionCode", deviceTreeStore.taskInfo?.missionCode);

          tabs1.value = [];
          activeName1.value = "";

          const res = await "/excelImport/import".post(formData, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          });
          if (res.code == 200) {
            ElMessage.success("导入成功");

            importResult.value = true;
            importTitle.value = "导入成功";

            importSuccessMessage.value = res.data;

            // 导入成功后刷新所有子组件
            refreshAllChildComponents();
          } else if (res.code == 299) {
            importSuccessMessage.value = [];
            importResult.value = false;
            importTitle.value = "导入失败";
            logCode.value = res.logCode;
            // 验证数据
            tabs1.value = res.data;
            activeName1.value = tabs1.value[0].tab;
            resultDialogVisible.value = true;
            importLoading.value = false;

            return;
          }else if(res.code == 298){
            importSuccessMessage.value = [];
             resultDialogVisible.value = true;
        logCode.value = res.logCode;
        logCodeFlag.value = true;
        logCodeTitle.value = res.msg;
        importTitle.value = "导入失败";
            return;
          }
        } catch (error: any) {
          console.error("导入错误:", error);
          importTitle.value = "导入失败";
          ElMessage.warning(error.data?.msg || "导入失败");
        } finally {
          importLoading.value = false;
          // 清空文件选择
          if (uploadRef.value) {
            uploadRef.value.clearFiles();
          }
          selectedFile.value = null;
        }
      })
      .catch(() => {
        // 用户取消，清空文件选择
        if (uploadRef.value) {
          uploadRef.value.clearFiles();
        }
      });
  } else if (type === "packet") {
    if (!file.raw) {
      return;
    }
    selectedFile.value = file.raw;
    try {
      const formData = new FormData();
      formData.append("file", file.raw);
      formData.append("deviceCode", currentNodeKey.value);

      tabs1.value = [];

      activeName1.value = "";

      const res = await "/api/import/import".post(formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });

      if (res.code == 200) {
        ElMessage.success("导入成功");
        if (departmentTreeRef.value) {
          departmentTreeRef.value.refreshRootTree(); // 调用子组件方法
        }
        //
      } else if (res.code == 298) {
        resultDialogVisible.value = true;
        logCode.value = res.logCode;
        logCodeFlag.value = true;
        logCodeTitle.value = res.msg;
        importTitle.value = "导入失败";
        // 验证数据

        return;
      }
    } catch (error: any) {
      //  departmentTreeRef.value.refreshRootTree(); // 调用子组件方法
      ElMessage.warning(error.data?.msg || "导入失败");
    } finally {
      importLoading.value = false;
      // 清空文件选择
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }
      selectedFile.value = null;
    }
  }
};
const dialogTitle = ref("");
const exportAction = async () => {
  productStore.setProductMarketStep(0);
  dialogTitle.value = "导出数据包";
  dialogVisible.value = true;
  actionType.value = "task";
};
// 错误日志
const logAction = async (logCode: string) => {
  if (!logCode) {
    ElMessage.warning("请先获取错误日志");
    return;
  }
  try {
    const res = await "/api/log/export".get(
      {
        logCode,
      },
      {
        responseType: "blob", // 指定响应类型为blob用于文件下载
      }
    );
    if (res.status === 200) {
      await handleFileDownload(res);
    } else {
      ElMessage.warning(res.data?.msg || "导出失败");
    }
  } catch (error: any) {
    ElMessage.warning(error.data?.msg || "导出失败");
  }
};
// 下载excel模板
const exportActionExcel = async () => {
  const res = await "/sAttachment/downloadExcelTemplate".post(
    {
      missionCode: deviceTreeStore.taskInfo?.missionCode,
    },
    {
      responseType: "blob", // 指定响应类型为blob用于文件下载
    }
  );

  if (res.status === 200) {
    // ElMessage.success("导出成功");
    await handleFileDownload(res);
    ElMessage.success("导出成功，文件已开始下载");
  } else {
    ElMessage.warning(res.data?.msg || "导出失败");
  }
};
// 刷新所有子组件的方法
// 使用 reactive 存储所有组件实例
const componentRefs = reactive<Record<string, any>>({});

// 刷新方法
const refreshAllChildComponents = async () => {
  await nextTick(); // 确保 DOM 已更新
  const currentComponent = componentRefs[activeName.value];

  console.log(currentComponent,788);

  if (!currentComponent) {
    console.log("❌ 当前组件实例为空");
    return;
  }
  if (typeof currentComponent.getList !== "function") {
    console.log(
      "❌ getList 方法不存在，当前组件的方法:",
      Object.keys(currentComponent).filter(
        (key) => typeof currentComponent[key] === "function"
      )
    );
    return;
  }
  currentComponent.getList();
};

// 上一步
const prevStep = () => {
  productStore.productMarketStep--;
};
// 下一步
const stepsNum = ref(0);
const nextStep = () => {
  stepsNum.value++;
};

/**
 * 保存采集任务
 */
const taskRef = ref();
const saveTask = async () => {
  const task = unref(taskRef);
  if (!task) {
    ElMessage.error("无法获取选中的节点信息");
    return;
  }

  // 获取选中的节点和表单数据

  const formData = await task.getFormData();

  if (!formData) {
    ElMessage.warning("请正确填写表单");
    return;
  }

  saveLoading.value = true;
  try {
    const res = await "/api/export/export".post(
      {
        ...formData,
        missionCode: deviceTreeStore.taskInfo?.missionCode,
      },
      {
        responseType: "blob", // 指定响应类型为blob用于文件下载
      }
    );

    // 处理文件下载
    await handleFileDownload(res);
    ElMessage.success("导出成功，文件已开始下载");
    dialogVisible.value = false;
    // fetchDepartment(); // 刷新数据
  } catch (error) {
    console.error("导出任务创建失败:", error);
    ElMessage.error("导出任务创建失败");
  } finally {
    saveLoading.value = false;
  }
};
/**
 * 处理文件下载
 * @param res 响应对象
 */
const handleFileDownload = async (res: any) => {
  const blob = new Blob([res.data], {
    type: res.headers["content-type"] || "application/octet-stream",
  });

  // 获取文件名
  const contentDisposition = res.headers["content-disposition"];
  let filename = "dataExport";
  if (contentDisposition) {
    const filenameMatch = contentDisposition.match(/filename="?(.+)"?/);
    if (filenameMatch && filenameMatch.length === 2) {
      filename = decodeURIComponent(filenameMatch[1]);
    }
  }

  // 创建下载链接
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", filename);
  document.body.appendChild(link);
  link.click();

  // 清理资源
  window.URL.revokeObjectURL(url);
  document.body.removeChild(link);
};
// 监听弹框显示状态
// 或者使用 immediate 选项确保初始化
watch(
  () => dialogVisible.value,
  (newVal) => {
    if (!newVal) {
      // 弹框关闭时重置
      productStore.setProductMarketStep(0);
      stepsNum.value = 0;
    }
  },
  { immediate: true }
);
onMounted(() => {
  calculateHeights();
  window.addEventListener("resize", calculateHeights);
});

onUnmounted(() => {
  window.removeEventListener("resize", calculateHeights);
});
</script>

<style scoped lang="less">
.el-card {
  overflow-x: auto;
}

:deep(.el-tabs__content) {
  overflow: visible;
}
:deep(.el-scrollbar__view) {
  // height: 100%;
}

.import-result {
  height: 100%;

  .import-result-container {
    height: 100%;
  }
}

// 修复 tabs 样式
:deep(.full-height-tabs) {
  height: 100% !important;

  .el-tabs__header {
    margin-bottom: 0; // 移除默认的底部间距
  }

  .el-tabs__content {
    height: calc(100% - 40px); // 减去 tabs 头部的高度
    overflow: hidden;

    .el-tab-pane {
      height: 100%;
    }
  }
}

.error-content-wrapper {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .error-details,
  .no-errors {
    margin-top: 15px;
    flex: 1;
    overflow-y: auto;
    max-height: 100%;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 16px;
    // background-color: #FAF7F7;
  }
}

// .error-details {
.error-item {
  margin-bottom: 16px;
  padding: 12px;
  background: white;
  border-radius: 4px;
  border: 1px solid rgba(251, 198, 198, 1);
  background-color: rgba(254, 240, 240, 0.5);
  // border-left: 4px solid #f56c6c;

  h4 {
    color: #f56c6c;
    font-weight: bold;
  }

  p {
    // color: #606266;
    margin: 4px 0;
    padding-left: 8px;
    color: #f56c6c;
  }
}

.no-errors {
  text-align: center;
  color: #67c23a;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.success-message {
  max-height: 400px;
  overflow-y: auto;
  padding: 16px;

  div {
    padding: 8px 12px;
    background: #f0f9ff;
    border-radius: 4px;
    margin-bottom: 8px;
    border-left: 4px solid #409eff;
  }
}

:deep(.el-descriptions__cell) {

    padding: 5px 11px !important;
}
.line {
      border-top: 1px var(--el-border-color) var(--el-border-style);
    display: block;
    height: 1px;
    margin: 18px 0 8px 0;
    width: 100%;
}
</style>
